package com.jakewharton.rxbinding4.component;

import static com.jakewharton.rxbinding4.internal.Preconditions.checkMainThread;

import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.openharmony.MainThreadDisposable;
import ohos.agp.components.Component;

final class ComponentScrollEventObservable extends Observable<ComponentScrollChangeEvent> {
    private final Component view;

    ComponentScrollEventObservable(Component view) {
        this.view = view;
    }

    @Override
    protected void subscribeActual(Observer<? super ComponentScrollChangeEvent> observer) {
        if (!checkMainThread(observer)) {
            return;
        }
        Listener listener = new Listener(view, observer);
        observer.onSubscribe(listener);
        view.setScrolledListener(listener);
    }

    static final class Listener extends MainThreadDisposable implements Component.ScrolledListener {
        private final Component view;
        private final Observer<? super ComponentScrollChangeEvent> observer;

        Listener(Component view, Observer<? super ComponentScrollChangeEvent> observer) {
            this.view = view;
            this.observer = observer;
        }

        @Override
        protected void onDispose() {
            view.setScrolledListener(null);
        }

        @Override
        public void onContentScrolled(Component v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
            if (!isDisposed()) {
                observer.onNext(ComponentScrollChangeEvent.create(v, scrollX, scrollY, oldScrollX, oldScrollY));
            }
        }
    }
}
